﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TiposComuns.Objectos;
using System.Runtime.CompilerServices;

namespace Servidor.Objectos
{
    /// <summary>
    /// Messages posted by the user or by his friends
    /// </summary>
    [Serializable]
    public class Wall
    {   
        private List<Post> mensagens = new List<Post>(); /*Sorted list of messages, ordered by the CompareTo
                                                                                 * method, defined in Post*/
        private SerializableDictionary<string, IDMsg> users = 
            new SerializableDictionary<string, IDMsg>();//Map between usernames and the number of the last post received for that user

        #region Modifiers
        public List<Post> Posts
        {
            get 
            {
                return mensagens;
            }
            set 
            {
                mensagens = value;
                mensagens.Sort();
            }
        }

        public SerializableDictionary<string, IDMsg> Users
        {
            get { return users; }
            set { users = value; }
        }
        #endregion

        public Wall()
        {
            this.users = new SerializableDictionary<string, IDMsg>();
            this.mensagens = new List<Post>();
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Remove(Post post)
        {
            this.Posts.Remove(post);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Post(Post post)
        {
            mensagens.Add(post);
            mensagens.Sort();
            if (!users.ContainsKey(post.User.Username))
                users.Add(post.User.Username, post.ID);
            else users[post.User.Username] = post.ID;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public List<Post> GetAfter(int id)
        {
            List<Post> list = new List<Post>();

            IEnumerable<Post> data = (from db in mensagens
                                                          where db.ID.ID > id 
                                                          && db.ID.isClient == true 
                                                          select db);
            
            foreach (Post p in data)
            {
                list.Add(p);
            }

            return list;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void PostAll(List<Post> list)
        {
            foreach (Post post in list)
            {
                this.Post(post);
            }
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public Dictionary<string, IDMsg> GetUsers()
        {
            return users;
        }
    }
}
